use futures_util::StreamExt;
use serde_json::json;
use tauri::{AppHandle, command, Runtime, Emitter};
use tokio::fs::File;
use tokio::io::AsyncWriteExt;
use crate::models::*;
use crate::InstallExt;

#[command]
pub(crate) async fn install<R: Runtime>(
    app: AppHandle<R>,
    payload: InstallRequest,
) {
    let _ = app.install().install(payload);
}

#[command]
pub(crate) async fn download<R: Runtime>(
    app: AppHandle<R>,
    payload: DownloadRequest,
) {
    let url = payload.url;
    let path = payload.path;
    match reqwest::get(url).await {
        Ok(res) => {
            let total = res.content_length().unwrap_or(0);
            let mut progress_total = 0;
            if let Ok(mut file) = File::create(path).await {
                let mut stream = res.bytes_stream();
                while let Some(Ok(item)) = stream.next().await {
                    match file.write_all(&item).await {
                        Ok(_) => {
                            let progress = item.len();
                            progress_total = progress + progress_total;
                            let _ = app.emit("/file/download", json!({
                                "progressTotal": progress_total,
                                "total": total,
                            }));
                        }
                        Err(_) => {}
                    }

                }
            }
        }
        Err(_) => {}
    }
}